package com.viewshine.nettydemo.springBeanMethod.nettyServer;

import com.viewshine.nettydemo.springBeanMethod.config.property.NettyServerConnectObj;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName SpringEchoServer
 * @Author rhb
 * @Description SpringBean 启动客户端
 * @Date 2019-01-18 9:13
 * @Version 1.0
 **/
@Component
@Slf4j
public class SpringEchoServer {

    @Autowired
    private NettyServerConnectObj nettyServerConnectObj;

    /**
     * 初始化bean 启动该方法
     */
    @PostConstruct
    public void initMethod() {
        log.debug("【NettyServer start port {}!】", nettyServerConnectObj.getPort());
        Thread t = new Service();
        t.setDaemon(true);
        t.setName("NettyServer");
        t.start();
        log.debug("【NettyServer is start !】");
    }


    /**
     * @author David
     */
    class Service extends Thread {
        public void run() {
            try {
                new SpringEchoServer().start(nettyServerConnectObj.getPort());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * SpringEchoServer start方法
     *
     * @throws Exception
     */
    public void start(Integer port) throws Exception {
        //EventLoopGroup是用来处理IO操作的多线程事件循环器
        //bossGroup 用来接收进来的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //workerGroup 用来处理已经被接收的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //启动 NIO 服务的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    //配置 Channel
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
//                            pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//                            pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new SpringEchoServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，开始接收进来的连接
            ChannelFuture f = b.bind(port).sync();
            // 等待服务器 socket 关闭 。
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
